package com.candy.sys.controller;


import cn.hutool.crypto.SmUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.candy.common.exception.BusinessException;
import com.candy.common.result.R;
import com.candy.sys.entity.User;
import com.candy.sys.service.IUserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.candy.common.controller.BaseController;
import io.swagger.annotations.Api;

/**
 * <p>
 * 用户 前端控制器
 * </p>
 *
 * @author pxs
 * @since 2021-06-26
 */
@Api(tags="用户")
@RestController
@RequestMapping("/sys/user")
public class UserController extends BaseController<IUserService, User> {

	@Value("${token.defalut.password:123456}")
	private String defalutPassword;

	@Override
	@ApiOperation(value = "列表")
	@GetMapping("/list")
	public R list(User user)
	{
		LambdaQueryChainWrapper<User> userLambdaQueryChainWrapper = baseService.lambdaQuery();
		if(StringUtils.isNotEmpty(user.getRealName()))
		{
			userLambdaQueryChainWrapper.like(User::getRealName, user.getRealName());
			user.setRealName(null);
		}
		userLambdaQueryChainWrapper.setEntity(user);
		userLambdaQueryChainWrapper.orderByAsc(User::getOrderNum);
		IPage<User> pageModel = baseService.page(getPage(), userLambdaQueryChainWrapper.getWrapper());
		return R.success(pageModel);
	}

	@Override
	@ApiOperation(value = "新增")
	@PostMapping
	public R save(@Validated @RequestBody User user)
	{
		if(!baseService.isUniqueLoginName(user))
		{
			throw new BusinessException("登录名重复");
		}
		if(StringUtils.isEmpty(user.getPassword()))
		{
			user.setPassword(SmUtil.sm3(defalutPassword));
		}
		else
		{
			user.setPassword(SmUtil.sm3(user.getPassword()));
		}
		return R.success(baseService.save(user));
	}

	@Override
	@ApiOperation(value = "修改")
	@PutMapping
	public R edit(@Validated @RequestBody User user)
	{
		if(StringUtils.isEmpty(user.getLoginName()))
		{
			throw new BusinessException("用户名不能为空");
		}
		if(!baseService.isUniqueLoginName(user))
		{
			throw new BusinessException("登录名重复");
		}
		if(StringUtils.isNotEmpty(user.getPassword()))
		{
			user.setPassword(SmUtil.sm3(user.getLoginName()+user.getPassword()));
		}
		return R.success(baseService.updateById(user));
	}
}
